﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UIDemo.Utils
{
    public class ImageUtil
    {
        public static void AddImageToCollection(string key, ImageList imageList, Image image)
        {
            if (imageList == null)
                return;
            if (imageList.ImageSize == image.Size)
            {
                imageList.Images.Add(key, image);
                return;
            }
            using (Bitmap imageAsBitmap = new Bitmap(image))
            {
                Bitmap bm = new Bitmap(imageList.ImageSize.Width, imageList.ImageSize.Height);
                Graphics g = Graphics.FromImage(bm);
                g.Clear(imageList.TransparentColor);
                Size size = imageAsBitmap.Size;
                int x = Math.Max(0, (bm.Size.Width - size.Width) / 2);
                int y = Math.Max(0, (bm.Size.Height - size.Height) / 2);
                g.DrawImage(imageAsBitmap, x, y, size.Width, size.Height);
                imageList.Images.Add(key, bm);
            }
        }
        public static void AddImageToCollection(string key, ImageList imageList, Icon image)
        {
            if (imageList == null)
                return;
            if (imageList.ImageSize == image.Size)
            {
                imageList.Images.Add(key, image);
                return;
            }
            using (Bitmap imageAsBitmap = image.ToBitmap())
            {
                Bitmap bm = new Bitmap(imageList.ImageSize.Width, imageList.ImageSize.Height);
                Graphics g = Graphics.FromImage(bm);
                g.Clear(imageList.TransparentColor);
                Size size = imageAsBitmap.Size;
                int x = Math.Max(0, (bm.Size.Width - size.Width) / 2);
                int y = Math.Max(0, (bm.Size.Height - size.Height) / 2);
                g.DrawImage(imageAsBitmap, x, y, size.Width, size.Height);
                imageList.Images.Add(key, bm);
            }
        }
    }
}
